﻿#include "filehandler.h"

FileHandler *FileHandler::instance = nullptr;
QMutex *FileHandler::insMutex = new QMutex();

FileHandler *FileHandler::getInstance()
{
    QMutexLocker locker(insMutex);
    if(!instance) {
        instance = new FileHandler();
    }
    return instance;
}

FileHandler::FileHandler()
    : defaultDirPath(QDir::currentPath() + "/source"), defaultOutPath(QDir::currentPath() + "/appOut")
{
    fileDirPath = defaultDirPath;
    outDirPath = defaultOutPath;
    handlerInit();
}

FileHandler::~FileHandler()
{
    delete instance;
    delete insMutex;
    instance = nullptr;
    insMutex = nullptr;
}

const QString FileHandler::getFileDir()
{
    return fileDirPath;
}

const QString FileHandler::getOutDir()
{
    return outDirPath;
}

void FileHandler::setFileDir(const QString &path)
{
    fileDirPath = path;
}

void FileHandler::setDefaultFileDir()
{
    fileDirPath = defaultDirPath;
}

QStringList FileHandler::getFileList()
{
    return fileDir.entryList();
}

QString FileHandler::readFile(const QString &name)
{
    QFile file(name);
    if(file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QTextStream stream(&file);
        return stream.readAll();
    } else {
        return QString();
    }
}

void FileHandler::writeFile(const QString &name, int *data, int length)
{
    if(data) {
        QFile file(name);
        if(file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) {
            QTextStream stream(&file);
            int *temp = data;
            for(int i = 0; i < length; i++) {
                stream << *temp << endl;
                temp++;
            }
            delete []data;
        }
    }
}

void FileHandler::handlerInit()
{
    fileDir.setPath(fileDirPath);
    if(!fileDir.exists()) {
        fileDir.mkpath(fileDirPath);
    }
    fileDir.setSorting(QDir::Name);
    fileDir.setFilter(QDir::Files);

    outDir.setPath(outDirPath);
    if(!outDir.exists()) {
        outDir.mkpath(outDirPath);
    }
    outDir.setSorting(QDir::Name);
    outDir.setFilter(QDir::Files);
}
